package com.ruoyi.web.controller;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import com.ruoyi.web.controller.Util.FileUploadUtil;
import org.apache.http.entity.ContentType;
import org.json.JSONObject;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 文字转语音工具类
 */
@Controller
@RequestMapping("/system/getspeech")
public class TexttoSpeechController {
    //设置APPID/AK/SK
    public static final String APP_ID = "26682908";
    public static final String API_KEY = "k4SCxuy7yPSOe3zv3s7gsUXj";
    public static final String SECRET_KEY = "BCmo1GuCbrTXm9zBXpn6ouAC2C8XpLSw";

    @PostMapping("/get")
    @ResponseBody
    public String TexttoSpeech(@RequestParam("text") String text,
                               @RequestParam("userId") Long userId) {
//         初始化一个AipSpeech
        AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
        System.setProperty("aip.log4j.conf", "ruoyi-admin/src/main/resources/log4j.properties");
        // 调用接口
        TtsResponse res = client.synthesis(text, "zh", 1, null);
        byte[] data = res.getData();
        JSONObject res1 = res.getResult();
        if (data != null) {
            try {
                String output="D:\\Work\\temp\\"+userId+".mp3";
                Util.writeBytesToFileSystem(data, output);//output是文件生成地址
                File temp = new File(output);
                FileInputStream fileInputStream = new FileInputStream(temp);

                MultipartFile multipartFile = new MockMultipartFile(temp.getName(), temp.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                System.out.println("111111111111");
                FileUploadUtil fileUploadUtil=new FileUploadUtil();
                String path = fileUploadUtil.updateFileReturnPath(multipartFile);
                temp.delete();
                return path;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (res1 != null) {
            System.out.println(res1.toString(2));
        }
        return null;
    }
}
